<template>
  <div class="component-upload-image">
    <el-upload
      :action="uploadImgUrl"  
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="1"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      name="file"
      :show-file-list="false"
      :headers="headers"
      :file-list="fileList"
      :class="{ hide: !showAdd }"
    >
      <template v-if="fileList.length">
        <div class="has-img" @click.stop>
          <div class="img-mask flex-center">
            <i class="el-icon-delete del-icon" @click="handleRemove"></i>
          </div>
          <el-image class="upload-icon"
          :src="fileList[0].url" fit="contain"></el-image>
        </div>
      </template>
      <template v-else>
        <svg-icon class="upload-icon" :icon-class="iconName"></svg-icon>
      </template>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    iconName: String
  },
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadOss", // 上传的图片服务器地址
      headers: {
        Authorization: getToken(),
      },
      fileList: [],
      showAdd: true,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val.map(i => i.url) : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            let obj = {}
            obj.url = item
            return obj;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      // const findex = this.fileList.map((f) => f.url).indexOf(file.url);
      this.fileList.splice(0, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code == 200) {
        this.fileList.push({
          url: res.url
        });
        // this.fileList.push(res.data);
        this.$emit("input", this.listToString(this.fileList));
        this.loading.close();
        this.$emit('change', res.url)
      }
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$message.error(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.showAdd = false
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 1 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.showAdd = true
      this.loading.close();
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
::v-deep .el-upload{
  .has-img{
    position: relative;
    &:hover{
      .img-mask{
        display: block;
      }      
    }
    .img-mask{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0,0,0,.3);
      z-index: 99;
      display: none;
    }
    .del-icon{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 32px;
      color: #fff;
    }
  }
  
}
</style>

